package com.asking.service;

import com.asking.dao.AnswerMapper;
import com.asking.domain.Answer;
import com.asking.domain.User;
import com.asking.pojo.EsAnswer;
import com.asking.service.es.AnswerRepository;
import com.asking.vo.ResultVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: 宋定鑫
 * @Date: 2018/10/17 15:41
 */
@Service
@Transactional
public class AnswerService {

    @Resource
    private AnswerMapper answerMapper;
    @Resource
    private AnswerRepository answerRepository;

    public void updata(Answer answer) {
        Answer answer1 = answerMapper.selectByPrimaryKey(answer.getId());
        answer.setTime(answer1.getTime());
        answerMapper.updateByPrimaryKey(answer);
    }

    public void add(Answer answer) {
        answer.setTime(new Date());
        answerMapper.insert(answer);
    }


    public Answer selectByAnswer(Integer id) {
        Answer answer = answerMapper.selectByPrimaryKey(id);
        return answer;

    }

    public ResultVo findAll(Integer page, Integer rows) {
        PageHelper.startPage(page, rows);// PageHelper 对紧跟着它的第一条sql语句进行分页操作
        List<Answer> answers = answerMapper.selectAll();
        PageInfo<Answer> info = new PageInfo<>(answers);
        ResultVo resultVo = new ResultVo();
        resultVo.setTotal(info.getTotal());
        resultVo.setRows(info.getList());
        return resultVo;
    }

    public void deleteidanswer(Integer id) {
        answerMapper.deleteByPrimaryKey(id);
    }


    public void pare() {
        List<Answer> answers = answerMapper.selectAll();

        List<EsAnswer> esAnswers = new ArrayList<>();

        for (Answer a : answers) {
            EsAnswer esAnswer = new EsAnswer();
            esAnswer.setId(a.getId());
            esAnswer.setPid(a.getPid());
            esAnswer.setSupport(a.getSupport());
            esAnswer.setText(a.getText());
            esAnswer.setTime(a.getTime());
            esAnswer.setUid(a.getUid());
            esAnswers.add(esAnswer);
        }
       this.answerRepository.deleteAll();
        answerRepository.saveAll(esAnswers);

    }
}
